<template>
  <div>
    <div class="spu">
      <Card>
        <p slot="title">商品概要</p>
        <Form :model="spuForm" ref="spuForm" :label-width="80" label-position="left" :rules="spuFormRule" inline>
          <Row>
            <i-col span="12">
              <FormItem label="商品标题" prop="title">
                <Input v-model="spuForm.title" style="width: 80%;" placeholder="这个商品显示的标题..." />
              </FormItem>
            </i-col>
            <i-col span="12">
              <FormItem label="商品分类" prop="selectClassify">
                <Select v-model="spuForm.selectClassify" multiple>
                  <i-option v-for="item in classifyTree" :value="item.id" :key="item.id">
                    <span :class="{childItem: item.parentId}"></span>{{ item.name }}
                  </i-option>
                </Select>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <i-col span="12">
              <FormItem label="商品标签" prop="goodsLabel">
                <Select v-model="spuForm.goodsLabel" style="width: 170px;" multiple @on-change="labelChange">
                  <Option v-for="label in labels" :key="label.id" :value="label.id">{{label.label}}</Option>
                </Select>
                <div style="position: absolute;left: 170px;top: 0;">
                  <Button type="text" @click="otherLabel">我要自己输入</Button>
                  <Input v-model="spuForm.goodsLabelInput" v-show="labelInput" style="width: 110px;" placeholder="比如时尚、经典..."/>
                  <Button v-show="labelInput" type="primary" @click="addLabel">加入</Button>
                </div>
              </FormItem>
            </i-col>
            <i-col span="12">
              <FormItem label="商品单位" prop="goodsUnit">
                <Select v-model="spuForm.goodsUnit" style="width: 100px;">
                  <Option v-for="unit in units" :key="unit.id" :value="unit.id">{{unit.unit}}</Option>
                </Select>
              </FormItem>
              <div style="position: absolute;left: 180px;top: 0;">
                <Button type="text" @click="otherUnit">我要自己输入</Button>
                <Input v-model="spuForm.goodsUnitInput" v-show="unitInput" style="width: 110px;" placeholder="比如个、件、套..." />
                <Button v-show="unitInput" type="primary" @click="addUnit">加入</Button>
              </div>
            </i-col>
          </Row>
          <Row>
            <i-col span="4">
              <FormItem label="是否新品">
                <i-switch size="large" true-value="1" false-value="0" v-model="spuForm.isNew">
                  <span slot="open">开启</span>
                  <span slot="close">关闭</span>
                </i-switch>
              </FormItem>
            </i-col>
            <i-col span="4">
              <FormItem label="是否推荐">
                <i-switch size="large" true-value="1" false-value="0" v-model="spuForm.isRecommend">
                  <span slot="open">开启</span>
                  <span slot="close">关闭</span>
                </i-switch>
              </FormItem>
            </i-col>
            <i-col span="4">
              <FormItem label="是否清仓">
                <i-switch size="large" true-value="1" false-value="0" v-model="spuForm.isClear">
                  <span slot="open">开启</span>
                  <span slot="close">关闭</span>
                </i-switch>
              </FormItem>
            </i-col>
            <i-col span="12">
              <FormItem label="商品权重">
                <Slider v-model="spuForm.sortWeight" :tip-format="format" @on-change="valueChange"/>
              </FormItem>
            </i-col>
          </Row>
          <div class="goodsPhoto">
          <span class="title">
            <p style="margin-top: 40px;">商品主图</p>
            <p style="color: #ed3f14;line-height: 10px;">至少一张</p>
          </span>
            <Upload
              v-for="i in uploadSize"
              :key="i"
              :show-upload-list="true"
              :format="['jpg','jpeg','png']"
              :max-size="2048"
              :on-format-error="handleFormatError"
              :on-exceeded-size="handleMaxSize"
              :before-upload="handleBeforeUpload"
              action="#">
              <div style="width: 100px;height:100px;line-height: 100px;position: relative;" @click="saveImgNumber (i)">
                <Icon type="camera" size="20"></Icon>
                <div class="img" v-if="imgDataArr[i]">
                  <img :src="imgDataArr[i]" alt="" width="100" height="100" style="display: block;"/>
                  <div class="tag" v-if="i === 1">
                    <Tag color="blue">主图</Tag>
                  </div>
                  <div class="upload-list-cover" @click.stop>
                    <Icon type="ios-eye-outline" @click.stop="handleView(i)"></Icon>
                    <Icon type="ios-trash-outline" @click.stop="handleRemove(i)"></Icon>
                  </div>
                </div>
              </div>
            </Upload>
          </div>
        </Form>
      </Card>
    </div>
    <Modal v-model="imgShow" width="50" :styles="{top: '20px'}">
      <div style="height: 400px; width: 400px;margin: 0 auto;">
        <img :src="bigImg" alt="" height="100%">
      </div>
    </Modal>
  </div>
</template>

<script>
export default {
  name: 'goods-spu',
  data () {
    return {
      bigImg: '',
      imgShow: false,
      // 商品图片切割数据
      imgDataArr: [],
      imgBlobArr: [],
      // spu表单数据
      spuForm: {
        title: '',
        // spuName: '',
        goodsLabel: [],
        goodsUnit: '',
        goodsUnitInput: '', // 商品单位输入添加
        goodsLabelInput: '',
        selectClassify: [],
        goodsStatus: '0',
        goodsRemark: '',
        isNew: '0',
        isRecommend: '0',
        isClear: '0',
        sortWeight: 0
      },
      unitInput: false,
      labelInput: false,
      uploadSize: 5, // 文件选择框个数，动态变化
      imgNumber: -1, // 图片位置
      // 商品单位数据
      units: [],
      labels: [],
      // 商品分类数据
      classifyTree: [],
      spuFormRule: {
        title: [
          { required: true, message: '商品标题不能为空', trigger: 'blur' }
        ],
        goodsUnit: [
          { required: true, message: '商品单位不能为空', trigger: 'change', type: 'number' }
        ],
        selectClassify: [
          { required: true, message: '商品分类不能为空', trigger: 'change', type: 'array', min: 1 }
        ]
      },
      isAuditing: false,
      goodsId: '',
      addImages: [],
      firstImage: {}
    }
  },
  methods: {
    addUnit () {
      let params = {
        unit: this.spuForm.goodsUnitInput
      }
      // /goods/manager/add/goods/unit /goods/manager/add/goods/label
      this.$ajax.post('/goods/manage/add/unit/page', JSON.stringify(params)).then((res) => {
        if (res.data.success) {
          this.units.push({
            id: res.data.data.id,
            unit: res.data.data.unit
          })
          this.unitInput = false
          this.$Message.success('添加成功，请再次选择')
        }
      })
    },
    addLabel () {
      let params = {
        label: this.spuForm.goodsLabelInput
      }
      // /goods/manager/add/goods/unit /goods/manager/add/goods/label
      this.$ajax.post('/goods/manage/add/label/page', JSON.stringify(params)).then((res) => {
        if (res.data.success) {
          this.labels.push({
            id: res.data.data.id,
            label: res.data.data.label
          })
          this.labelInput = false
          this.$Message.success('添加成功，请再次选择')
        }
      })
    },
    setImgData (data, blob) {
      this.$set(this.imgDataArr, this.imgNumber, data)
      // this.imgDataArr.push(data)
      this.$set(this.imgBlobArr, this.imgNumber, blob)
      // this.imgBlobArr[this.imgNumber] = blob
      if (this.isAuditing) {
        this.addImages[this.imgNumber] = blob
      }
    },
    getSpuData () {
      let spuData = null
      console.log(this.spuForm)
      this.$refs.spuForm.validate((valid) => {
        if (valid) {
          // this.arrUtil(this.imgBlobArr)
          if (!this.imgBlobArr[1]) {
            this.$Message.error('必须添加第一张图片作为主图')
          } else {
            let goodsMain = {
              title: this.spuForm.title,
              isNew: this.spuForm.isNew,
              isRecommend: this.spuForm.isRecommend,
              isClear: this.spuForm.isClear,
              sortWeight: this.spuForm.sortWeight
            }
            let images = this.imgBlobArr
            let goodsCategoryIds = this.spuForm.selectClassify
            let unitId = this.spuForm.goodsUnit
            spuData = {
              goodsMain,
              images,
              goodsCategoryIds,
              unitId,
              labelIds: this.spuForm.goodsLabel,
              addImages: this.addImages,
              deleteImage: this.firstImage
            }
          }
        } else {
          this.$Message.error('请填写完整的信息')
        }
      })
      return spuData
    },
    saveImgNumber (i) {
      this.imgNumber = i
    },
    otherUnit () {
      this.unitInput = true
    },
    otherLabel () {
      this.labelInput = true
    },
    labelChange (val) {
      if (val.length > 2) {
        val.length = 2
        this.$set(this.spuForm, 'goodsLabel', val)
        this.$Message.warning('标签最多两个')
      }
    },
    // 商品权重值回显
    format (val) {
      return val
    },
    valueChange (val) {
      this.$ajax.get('/goods/manage/real/time/sort/weight', {params: {sortWeight: val}})
        .then(res => {
          if (res.data.success) {
            this.$Message.info('当前权重超过' + res.data.data * 100 + '%的商品')
          }
        })
    },
    // 文件格式不是图片时提醒
    handleFormatError () {
      this.$Message.error('必须要是图片(jpg,jpeg,png)格式')
    },
    // 图片超出大小时提醒
    handleMaxSize () {
      this.$Message.error('图片太大了，我受不了了')
    },
    // 上传图片前触发，阻止上传进入切图操作
    handleBeforeUpload (e) {
      let spuE = {
        e,
        name: 'spu'
      }
      this.$emit('setImage', spuE)
      return false
    },
    // 图片放大
    handleView (index) {
      this.imgShow = true
      this.bigImg = this.imgDataArr[index]
    },
    // 图片删除
    handleRemove (index) {
      this.$Modal.confirm({
        title: '你不要这张图片了吗？',
        content: '<p>你要是觉得这张图不好看，可以点不要了，要是点错了，点留着</p>',
        okText: '不要了',
        cancelText: '留着',
        onOk: () => {
          if (this.isAuditing && this.imgDataArr[index].length < 100) {
            // /remove/goods/main/image/audit/page
            let url = this.imgDataArr[index].substring(42)
            let params = {
              goodsId: this.goodsId,
              gmImagePath: [url]
            }
            if (index === 1) {
              this.firstImage = params
              this.$set(this.imgDataArr, index, undefined)
              // this.imgDataArr.push(data)
              this.$set(this.imgBlobArr, index, undefined)
              return
            }
            this.$ajax.post('/goods/manage/remove/goods/main/image/audit/page', JSON.stringify(params)).then(res => {
              if (res.data.success) {
                this.imgDataArr[index] = undefined
                this.imgBlobArr[index] = undefined
                this.$Message.info('已删除')
                this.handleView(index) // 马上更新
                this.imgShow = false // 更新完隐藏查看框
              }
            })
          } else {
            this.imgDataArr[index] = undefined
            this.imgBlobArr[index] = undefined
            this.$Message.info('已删除')
            this.handleView(index) // 马上更新
            this.imgShow = false // 更新完隐藏查看框
          }
        },
        onCancel: () => {
          this.$Message.info('留着')
        }
      })
    },
    setInitData (data) {
      this.isAuditing = true
      this.goodsId = data.id
      this.spuForm.title = data.title
      this.spuForm.selectClassify = data.selectClassify
      this.spuForm.goodsLabel = data.goodsLabel
      this.spuForm.goodsUnit = data.unitId
      this.spuForm.isNew = data.isNew + ''
      this.spuForm.isRecommend = data.isRecommend + ''
      this.spuForm.isClear = data.isClear + ''
      this.spuForm.sortWeight = data.sortWeight
      this.imgDataArr = [...(data.mainImages)]
      this.imgBlobArr = [...(data.mainImages)]
    }
  },
  created () {
    this.$ajax.get('/goods/manage/get/category/unit/label/list').then((res) => {
      this.labels = res.data.data.goodsLabelList
      this.units = res.data.data.goodsUnitList
      res.data.data.goodsCategoryTreeList.forEach((item, index) => {
        this.classifyTree.push(item)
        this.classifyTree.push(...item.childCategoryList)
      })
    })
  }
}
</script>

<style scoped>
  .goodsPhoto{
    height: 100px;
  }
  .goodsPhoto .title{
    /*line-height: 100px;*/
    font-size: 12px;
    font-weight: 800;
    margin-right: 20px;
    float: left;
  }
  .img{
    margin-right: 10px;
    border-radius: 10px;
    position: absolute;
    top: 0;
    left: 0;
    overflow: hidden;
  }
  .upload-list-cover{
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0,0,0,.6);
    text-align: center;
  }
  .img:hover .upload-list-cover{
    display: block;
  }
  .upload-list-cover i{
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 45px 5px 0 0;
  }
  .tag{
    position: absolute;
    top: -35px;
    right: 0;
  }
  .ivu-form-item{
    width: 100%;
  }
  .ivu-upload{
    display: inline-block;
    width:100px;
    height: 100px;
    text-align: center;
    margin-right: 10px;
    border: 1px solid #ddeed1;
    cursor: pointer;
  }
  .childItem{
    padding-left: 10px;
  }
  .spu{
    padding: 4px;
    background-color: #eee;
    margin-bottom: 10px;
  }
</style>
